#include"Socket.hpp"
#include"Protocal.hpp"
#include<ctime>
#include<cassert>
#include<unistd.h>
void Usage(const std::string &proc)
{
    std::cout<<"Usage: "<<proc<<" serverip serverport\n"<<std::endl;
    exit(1);
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    Sock sockfd;
    sockfd.Socket();
    bool r = sockfd.Connet(serverip, serverport);
    if(!r) return 1;

    srand(time(nullptr));
    int cnt = 10;
    string opers = "+-*/%~?";

    string inbuffer_stream;
    while(cnt--)
    {
        std::cout<<"--------------------------第"<<cnt<<"次测试"<<std::endl;
        int x = rand()%100 + 1;
        usleep(1255);
        int y = rand()%100;
        usleep(2356);
        char op = opers[rand()%opers.size()];
        Request rq(x, y, op);
        rq.DebugPrint();

        std::string package;
        rq.Serialize(&package);
        package = Encode(package);  
        std::cout<<"这是最新的发出的请求"<<std::endl;      

        write(sockfd.GetFd(), package.c_str(), package.size());

        char buffer[128];
        ssize_t n = read(sockfd.GetFd(), buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n];
            inbuffer_stream += buffer;
            string content;
            bool r = Decode(inbuffer_stream, &content);
            assert(r);

            Response rp;
            r = rp.Deserialize(content);
            assert(r);
            rp.DebugPrint();
        }

        sleep(1);
    }

    sockfd.Close();

    std::cout<<"--------------------------------"<<std::endl;
    return 0;
}